<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="配置" prop="configId">
        <el-select
          v-model="queryParams.configId"
          placeholder="请选择配置"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="config in configList"
            :key="config.id"
            :label="config.name"
            :value="config.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作类型" prop="operationType">
        <el-select
          v-model="queryParams.operationType"
          placeholder="请选择操作类型"
          clearable
          class="!w-240px"
        >
          <el-option label="人脸识别" value="face_recognition" />
          <el-option label="配置创建" value="config_create" />
          <el-option label="配置更新" value="config_update" />
          <el-option label="配置删除" value="config_delete" />
          <el-option label="记录删除" value="record_delete" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="成功" :value="1" />
          <el-option label="失败" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="danger"
          plain
          @click="handleCleanLog"
          v-hasPermi="['ai:face-log:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 清空日志
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" width="80" />
      <el-table-column label="配置" align="center" prop="configId" width="120">
        <template #default="scope">
          {{ getConfigName(scope.row.configId) }}
        </template>
      </el-table-column>
      <el-table-column label="操作类型" align="center" prop="operationType" width="120">
        <template #default="scope">
          <el-tag :type="getOperationTypeTag(scope.row.operationType)">
            {{ getOperationTypeName(scope.row.operationType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作描述" align="center" prop="operationDesc" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">成功</el-tag>
          <el-tag v-else type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="耗时(ms)" align="center" prop="duration" width="100" />
      <el-table-column label="错误信息" align="center" prop="errorMsg" :show-overflow-tooltip="true" />
      <el-table-column label="IP地址" align="center" prop="userIp" width="120" />
      <el-table-column label="用户代理" align="center" prop="userAgent" :show-overflow-tooltip="true" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
          >
            详情
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['ai:face-log:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 详情弹窗 -->
  <el-dialog v-model="detailVisible" title="日志详情" width="800px">
    <div v-if="detailData">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="日志编号">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="配置名称">{{ getConfigName(detailData.configId) }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getOperationTypeTag(detailData.operationType)">
            {{ getOperationTypeName(detailData.operationType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detailData.status === 1" type="success">成功</el-tag>
          <el-tag v-else type="danger">失败</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="耗时">{{ detailData.duration }}ms</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ detailData.userIp }}</el-descriptions-item>
        <el-descriptions-item label="操作描述" :span="2">
          {{ detailData.operationDesc }}
        </el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2">
          {{ detailData.errorMsg || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="用户代理" :span="2">
          {{ detailData.userAgent }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(detailData.createTime) }}
        </el-descriptions-item>
      </el-descriptions>
      
      <!-- 请求参数 -->
      <div class="mt-4" v-if="detailData.requestParams">
        <h4>请求参数</h4>
        <el-input
          type="textarea"
          :rows="6"
          :value="formatJson(detailData.requestParams)"
          readonly
        />
      </div>
      
      <!-- 响应结果 -->
      <div class="mt-4" v-if="detailData.responseResult">
        <h4>响应结果</h4>
        <el-input
          type="textarea"
          :rows="6"
          :value="formatJson(detailData.responseResult)"
          readonly
        />
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { getFaceLogPage, deleteFaceLog, getFaceLog, cleanFaceLog } from '@/api/ai/face'
import { getFaceConfigPage } from '@/api/ai/face'

/** 人脸日志 列表 */
defineOptions({ name: 'AiFaceLog' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const configList = ref([]) // 配置列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  configId: undefined,
  operationType: undefined,
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

// 详情弹窗
const detailVisible = ref(false)
const detailData = ref(null)

// 操作类型映射
const operationTypeMap = {
  face_recognition: '人脸识别',
  config_create: '配置创建',
  config_update: '配置更新',
  config_delete: '配置删除',
  record_delete: '记录删除'
}

// 操作类型标签颜色
const operationTypeTagMap = {
  face_recognition: 'primary',
  config_create: 'success',
  config_update: 'warning',
  config_delete: 'danger',
  record_delete: 'info'
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getFaceLogPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取配置列表 */
const getConfigList = async () => {
  try {
    const data = await getFaceConfigPage({ pageNo: 1, pageSize: 100 })
    configList.value = data.list
  } catch (error) {
    console.error('获取配置列表失败:', error)
  }
}

/** 获取配置名称 */
const getConfigName = (configId: number) => {
  if (!configId) return '-'
  const config = configList.value.find(item => item.id === configId)
  return config ? config.name : `配置${configId}`
}

/** 获取操作类型名称 */
const getOperationTypeName = (type: string) => {
  return operationTypeMap[type] || type
}

/** 获取操作类型标签颜色 */
const getOperationTypeTag = (type: string) => {
  return operationTypeTagMap[type] || 'default'
}

/** 格式化JSON */
const formatJson = (jsonStr: string) => {
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch (e) {
    return jsonStr
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 打开详情 */
const openDetail = async (row) => {
  try {
    detailData.value = await getFaceLog(row.id)
    detailVisible.value = true
  } catch (error) {
    message.error('获取详情失败')
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteFaceLog(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 清空日志 */
const handleCleanLog = async () => {
  try {
    // 清空的二次确认
    await message.confirm('确定要清空所有日志吗？此操作不可恢复！')
    // 发起清空
    await cleanFaceLog()
    message.success('清空成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getConfigList()
  getList()
})
</script>